<template>
  <div class="app-container">
    <el-card>
      <el-tabs v-model="activeTab">
        <el-tab-pane label="科室信息" name="patients">
          <!-- 科室信息标签页的内容 -->
          <div class="app-container">
            <!-- 搜索表单 -->
            <el-form
                :model="queryParams"
                ref="queryFormRef"
                size="small"
                :inline="true"
                v-show="showSearch"
                label-width="68px"
            >
              <el-form-item label="科室名称" prop="name">
                <el-input
                    v-model="queryParams.name"
                    placeholder="请输入科室名称"
                    clearable
                    @keyup.enter="handleQuery"
                />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">
                  搜索
                </el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">
                  重置
                </el-button>
              </el-form-item>
              <div class="form-right-area">
                <el-button icon="el-icon-back" type="primary" plain size="mini" @click="goBack">返回</el-button>
              </div>
            </el-form>

            <!-- 操作按钮行 -->
            <el-row :gutter="10" class="mb8">
              <el-col :span="1.5">
                <el-button
                    type="primary"
                    plain
                    icon="el-icon-plus"
                    size="mini"
                    @click="handleAdd"
                >
                  新增
                </el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button
                    type="success"
                    plain
                    icon="el-icon-edit"
                    size="mini"
                    :disabled="single"
                    @click="handleUpdate"
                >
                  修改
                </el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button
                    type="danger"
                    plain
                    icon="el-icon-delete"
                    size="mini"
                    :disabled="multiple"
                    @click="handleDelete"
                >
                  删除
                </el-button>
              </el-col>
              <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
            </el-row>

            <!-- 表格展示 -->
            <el-table
                v-loading="loading"
                :data="depList"
                @selection-change="handleSelectionChange"
                border
            >
              <el-table-column type="selection" width="55" align="center" />
              <el-table-column label="科室id" align="center" width="100" type="index" />
              <el-table-column label="科室名称" align="center" prop="name" />
              <el-table-column label="科室描述" align="center" prop="description" />
              <el-table-column label="科室所属医生数量" align="center" prop="doctorsNum" />
              <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template #default="scope">
                  <el-button
                      size="mini"
                      type="text"
                      icon="el-icon-edit"
                      @click="handleUpdate(scope.row)"
                  >
                    修改
                  </el-button>
                  <el-button
                      size="mini"
                      type="text"
                      icon="el-icon-delete"
                      @click="handleDelete(scope.row)"
                  >
                    删除
                  </el-button>
                  <el-button
                      size="mini"
                      type="text"
                      icon="el-icon-view"
                      @click="handleView(scope.row)"
                  >
                    查看
                  </el-button>
                </template>
              </el-table-column>
            </el-table>

            <!-- 分页组件 -->
            <el-pagination
                v-if="total > 0"
                v-model:current-page="queryParams.currentPage"
                v-model:page-size="queryParams.pageSize"
                :page-sizes="[1, 3, 10, 20]"
                :total="total"
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
            />

            <!-- 添加或修改对话框 -->
            <el-dialog :title="title" v-model="open" width="850px" append-to-body :close-on-click-modal="false" :before-close="handleDialogClose">
              <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
                <el-form-item label="科室名称" prop="name">
                  <el-input v-model="form.name" placeholder="请输入科室名称" />
                </el-form-item>
                <el-form-item label="科室描述" prop="description">
                  <el-input v-model="form.description" placeholder="请输入对科室的描述" />
                </el-form-item>
                <el-form-item label="医生数量">
                  <el-input v-model="form.doctorsNum" disabled placeholder="科室所属医生数量" />
                </el-form-item>
                <el-form-item label="所属医院">
                  <el-input v-model="route.params.name" disabled/>
                </el-form-item>
              </el-form>
              <template #footer>
                <div class="dialog-footer">
                  <el-button 
                    type="primary" 
                    @click="debouncedSubmitForm" 
                    :loading="submitLoading"
                    :disabled="submitLoading">
                    确 定
                  </el-button>
                  <el-button @click="cancel" :disabled="submitLoading">
                    取 消
                  </el-button>
                </div>
              </template>
            </el-dialog>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios';
import {addDep, delDep, getDep, updateDep} from "../../api/bigDep/bigDep.js";
import {findDepByHospitalId} from "../../api/hospital/hospital.js";
import router from "../../router/index.js";
// import Pagination from "../../components/Pagination/index.vue";

// 添加防抖函数
function debounce(fn, delay = 300) {
  let timer = null;
  return function(...args) {
    if (timer) clearTimeout(timer);
    timer = setTimeout(() => {
      fn.apply(this, args);
      timer = null;
    }, delay);
  };
}

const route = useRoute()
console.log('id:'+route.params.id);    // 应该能看到传递的 id
console.log('name:'+route.params.name); 
const activeTab = ref('patients')

// 遮罩层
const loading = ref(false);
// 提交按钮加载状态
const submitLoading = ref(false);
// 选中数组
const ids = ref([]);
// 非单个禁用
const single = ref(true);
// 非多个禁用
const multiple = ref(true);
// 显示搜索条件
const showSearch = ref(true);
// 总条数
const total = ref(0);
// 科室列表数据
const depList = ref([]);
// 弹出层标题
const title = ref('');
// 是否显示弹出层
const open = ref(false);

// 查询参数
const queryParams = ref({
  currentPage: 1,
  pageSize: 10,
  name: '',
  queryString: null,
  hospitalId: route.params.id
});

// 选择查询条件
const selectQueryCondition = () => {
  if (queryParams.value.name) {
    queryParams.value.queryString = queryParams.value.name;
  } else {
    queryParams.value.queryString = null;
  }
};

// 表单参数
const form = ref({
  id: null,
  name: null,
  doctorsNum: 0,
  description: null,
  hospitalId: route.params.id
});

// 表单校验规则
const rules = ref({
  name: [
    { required: true, message: '请输入科室名称', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入科室描述', trigger: 'blur' }
  ]
});

// 表单引用
const formRef = ref(null);
const queryFormRef = ref(null);

// 省的选项数据数组
const hospitalsOptions = ref([]);

const hospitalName = ref(route.params.name || '');

function findHospitals() {
  axios({
    url: '/hospital/findHospitals',
    method: 'get',
  }).then((res) => {
    console.log('医院列表响应:', res);
    if (res.data && res.data.code === 200) {
      hospitalsOptions.value = res.data.data || [];
    } else {
      hospitalsOptions.value = [];
      ElMessage.error((res.data && res.data.msg) || '获取医院列表失败');
    }
  }).catch(error => {
    console.error('获取医院列表失败:', error);
    hospitalsOptions.value = [];
    ElMessage.error('获取医院列表失败');
  });
}
function handleHospitalChange(hospitalId) {
  // 获取选中的 id (hospitalId)
  console.log('Selected province ID:', hospitalId);
  form.value.hospitalId = hospitalId;
  // 获取选中的 name
  const selectedHospital = hospitalsOptions.value.find(
      (hospital)=> hospital.id === hospitalId
  );

  if (selectedHospital) {
    console.log('Selected province name:', selectedHospital.name);
    //  你可以在这里将 selectedProvince.name 存储到 data 中，以便在其他地方使用
    form.value.hospitalName = selectedHospital.name; // 例如，添加到 form 对象
  }
}


// 获取列表数据
const getList = async () => {
  selectQueryCondition();
  loading.value = true;
  try {
    console.log('查询参数:', queryParams.value);
    const res = await findDepByHospitalId(queryParams.value);
    console.log('科室列表响应:', res);
      const responseData = res;
      if (Array.isArray(responseData)) {
        // 如果返回的是数组格式
        depList.value = responseData.rows;
        total.value = responseData.length;
      } else if (responseData && typeof responseData === 'object') {
        // 如果返回的是对象格式，包含 rows 和 total
        depList.value = responseData.rows || [];
        total.value = responseData.total || 0;
      } else {
        depList.value = [];
        total.value = 0;
      }
      console.log('处理后的科室列表:', depList.value);
  } catch (error) {
    console.error('获取列表数据失败:', error);
    depList.value = [];
    total.value = 0;
    ElMessage.error('获取列表数据失败');
  } finally {
    loading.value = false;
  }
};


/**
 * 分页
 */
// 添加分页处理方法
// 页面大小改变
const handleSizeChange = (val) => {
  queryParams.value.pageSize = val;
  getList();
}

// 页码改变
const handleCurrentChange = (val) => {
  queryParams.value.currentPage = val;
  getList();
}

// 取消按钮操作
const cancel = () => {
  // 如果正在提交中，不允许关闭
  if (submitLoading.value) {
    return;
  }
  open.value = false;
  reset();
};

// 对话框关闭处理函数
const handleDialogClose = (done) => {
  if (submitLoading.value) {
    ElMessage.warning('正在提交数据，请稍后...');
    return;
  }
  
  // 重置表单
  formRef.value?.resetFields();
  // 重置数据
  reset();
  // 确保提交按钮状态重置
  submitLoading.value = false;
  
  done();
};

// 表单重置
const reset = () => {
  form.value = {
    id: null,
    name: null,
    doctorsNum: 0,
    description: null,
    hospitalId: route.params.id
  };
};

// 搜索按钮操作
const handleQuery = () => {
  queryParams.value.currentPage = 1;
  getList();
};

// 重置按钮操作
const resetQuery = () => {
  if (queryFormRef.value) {
    queryFormRef.value.resetFields();
  }
  handleQuery();
};

// 多选框选中数据处理
const handleSelectionChange = (selection) => {
  ids.value = selection.map(item => item.id);
  single.value = selection.length !== 1;
  multiple.value = selection.length === 0;
};

// 新增按钮操作
const handleAdd = () => {
  reset();
  title.value = '添加';
  open.value = true;
};

// 修改按钮操作
const handleUpdate = async (row) => {
  reset();
  const id = row?.id || ids.value[0];
  if (!id) {
    console.error('未选择有效的科室信息');
    return;
  }

  try {
    const res = await getDep(id);
    console.log('获取科室详情响应:', res);
    if (res.code === 200) {
      form.value = {
        ...res.data,
        hospitalId: route.params.id
      };
      title.value = '修改';
      open.value = true;
    } else {
      ElMessage.error(res.msg || '获取科室信息失败');
    }
  } catch (error) {
    console.error('获取科室信息失败:', error);
    ElMessage.error('获取科室信息失败');
  }
};

// 提交表单操作
const submitForm = async () => {
  if (formRef.value) {
    try {
      // 防止重复提交
      if (submitLoading.value) {
        return;
      }
      
      // 表单验证
      await formRef.value.validate();
      
      // 立即设置提交状态为加载中
      submitLoading.value = true;

      let res;
      if (form.value.id !== null) {
        res = await updateDep(form.value);
      } else {
        // 确保新增时设置了医院ID
        form.value.hospitalId = form.value.hospitalId || route.params.id;
        res = await addDep(form.value);
      }

      console.log('提交表单响应:', res);
      if (res.code === 200) {
        ElMessage.success(form.value.id !== null ? '修改成功' : '新增成功');
        
        // 先刷新数据
        await getList();
        
        // 最后关闭对话框
        open.value = false;
      } else {
        ElMessage.error(res.msg || '操作失败');
      }
    } catch (error) {
      console.error('表单提交失败:', error);
      ElMessage.error('表单提交失败');
    } finally {
      // 延迟重置提交状态，确保按钮禁用效果明显
      setTimeout(() => {
        submitLoading.value = false;
      }, 500);
    }
  }
};

// 使用防抖包装提交函数
const debouncedSubmitForm = debounce(submitForm, 300);

// 删除按钮操作
const handleDelete = async (row) => {
  let deleteIds = row?.id || ids.value;
  // 如果是数组且长度为0，说明没有选择任何记录
  if (Array.isArray(deleteIds) && deleteIds.length === 0) {
    ElMessage.warning('请选择要删除的记录');
    return;
  }

  const confirmMessage = Array.isArray(deleteIds)
    ? `是否确认删除选中的 ${deleteIds.length} 条记录？`
    : `是否确认删除编号为"${deleteIds}"的记录？`;

  try {
    const confirmed = await ElMessageBox.confirm(confirmMessage, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });

    if (confirmed) {
      const res = await delDep(deleteIds);
      console.log('删除响应:', res);
      if (res.code === 200) {
        ElMessage.success('删除成功');
        // 重置选中状态
        ids.value = [];
        single.value = true;
        multiple.value = true;
        // 刷新列表
        getList();
      } else {
        ElMessage.error(res.msg || '删除失败');
      }
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除科室信息失败:', error);
      ElMessage.error('删除失败');
    }
  }
};

const handleView = async (row) => {
  console.log("row-id"+row.id);
  console.log("row-name"+row.name);
  console.log("hospitalId"+route.params.id);
  console.log("hospitalName"+route.params.name);
  // router.push("/showDoc")
  router.push({
    name: 'showDoc',
    params: {
      id: row.id,
      name:row.name,
      hospitalId: route.params.id,
      hospitalName: route.params.name
    }
  });
}

// 分页改变时触发
const handlePageChange = (val) => {
  queryParams.value.currentPage = val.page;
  queryParams.value.pageSize = val.limit;
  getList();
};

// 返回按钮处理函数
const goBack = () => {
  router.push('/listHospital');
};

onMounted(() => {
  console.log('组件挂载，开始获取数据...');
  console.log('路由参数:', route.params);
  getList();
  findHospitals();
});
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.form-right-area {
  margin-left: auto;
  display: flex;
  align-items: center;
  position: absolute;
  right: 20px;
  top: 0;
}

.doctor-info {
  display: flex;
  gap: 40px;
  padding: 20px;
}

.avatar-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 10px;
}

.avatar-container {
  width: 200px;
  height: 200px;
  border-radius: 8px;
  overflow: hidden;
  border: 1px solid #dcdfe6;
}

.avatar {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.info-form {
  flex: 1;
}

.doctor-form {
  max-width: 600px;
}

.qr-code {
  display: flex;
  align-items: center;
  gap: 20px;
  padding: 20px;
}

.qr-label {
  font-size: 14px;
  color: #606266;
}

.qr-image {
  width: 150px;
  height: 150px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  overflow: hidden;
}

.qr {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: #f5f7fa;
  color: #909399;
  font-size: 30px;
}

:deep(.el-tabs__nav) {
  background-color: #fff;
  padding: 0 20px;
}
</style>
